package com.itcs.app.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.itcs.app.model.Message;
import com.itcs.app.service.ItcsTraderecordsService;
import com.itcs.app.service.PayService;
import com.itcs.app.service.PayTypeService;
import com.itcs.app.util.ParamMap;
import com.itcs.rongyun.rongsdk.Response;

/**
 * 
 * @author LiuPeng
 * 
 */
@Api(value = "用户controller", tags = { "用户操作接口" })
@RestController
@RequestMapping("/user")
public class UserController {
	private static final Logger logger = LoggerFactory.getLogger(UserController.class);
	@Autowired
	private PayService payService;
	@Autowired
	private PayTypeService payTypeService;
	@Autowired
	private ItcsTraderecordsService itcsTraderecordsService;

	/**
	 * 发送入口请求（入口白名单下发） 发送请求时必须判断是否在附近的收费站500米范围内，如果超出不可调用该接口 TODO
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ApiOperation("发送入口请求（入口白名单下发）")
	@PostMapping("/inWhitelist")
	public Message inWhitelist(HttpServletRequest request, HttpServletResponse response, @ApiParam(name = "userId", value = "用户id", required = true) Long id, @ApiParam(name = "longitude", value = "经度", required = true) String longitude, @ApiParam(name = "latitude", value = "维度", required = true) String latitude) {

		// 返回
		/**
		 * 
		 * { "message": "成功", "code": 200 }
		 * 
		 * or { "message": "附近没有可支持在线支付收费站哦", "code": 2025 }
		 * 
		 */
		return new Message(200, "成功");
	}

	/**
	 * 发送出口支付请求（出口白名单下发） 查询表名：itcs_exit_whitelist_rgt
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ApiOperation("发送出口支付请求（出口白名单下发）")
	@GetMapping("/exitWhitelist")
	@PostMapping("/exitWhitelist")
	public Response exitWhitelist(HttpServletRequest request, HttpServletResponse response, @ApiParam(name = "userId", value = "用户id", required = true) Long userId, @ApiParam(name = "tollstationId", value = "广场号", required = true) String tollstationId) {
		// 参数
		ParamMap param = ParamMap.init(request);
//		TODO 是否需要权限验证
		return itcsTraderecordsService.sendExitWhitelist(param);
//		return new Message(200, "成功");
	}
	@ApiOperation("APP支付回调订单")
	@PostMapping("/pay")
	public Message pay(HttpServletRequest request, HttpServletResponse response, String userId,String traderecordsId
	/*
	 * @ApiParam(name = "userId", value = "用户id", required = true) Long id,
	 * 
	 * @ApiParam(name = "traderecordsId", value =
	 * "支付订单ID 由融云推送，接口到融云推送时跳出支付订单页面，点击确认支付", required = true) String
	 * traderecordsId
	 */) {
// TODO 验证是否是真的正数据
		Map<String, String> payMap = new HashMap<String, String>();
		
		if(userId==null || userId.trim().equals("")){
			userId = request.getHeader("userId");
		}
		
		payMap.put("userId", userId);
		payMap.put("traderecordsId", traderecordsId);

		logger.info("userId=" + userId + "traderecordsId=" + traderecordsId);
		
		Map<String, String> result = payService.payResult(payMap);
		
		logger.info("result===" + result);
		if ("1".equals(result.get("state"))) {
			// 成功
			return new Message(200, result.get("mess"));
		}else if("2019".equals(result.get("state"))){
			// 余额不足
		    return new Message(2019, result.get("mess"));
		} else {
			// 失败
			return new Message(0, result.get("mess"));
		}
	}

	/**
	 * 扣款方式 查询user_accout_info，判断金额，更新：user_customer_info表pay_method 字段
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ApiOperation("扣款方式")
	@PostMapping("/payMethod")
	public Message payMethod(HttpServletRequest request, HttpServletResponse response, @RequestParam(name = "userId", defaultValue = "1", required = true) Long id, @RequestParam(name = "payMethod", defaultValue = "1", required = true) Integer payMethod
	/*
	 * @ApiParam(name = "userId", value = "用户id", required = true) Long id,
	 * 
	 * @ApiParam(name = "payMethod", value = "扣款方式 0非自动扣款 1自动扣款（不需要密码）",
	 * required = true) Integer payMethod
	 */) {

		// 根据用户ID，更新扣款方式
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("payMethod", payMethod);
		paramMap.put("userId", id);
		Map<String, Object> result = payTypeService.updateMethod(paramMap);
		if ("200".equals(result.get("code"))) {
			// 返回成功
		} else {
			// 返回失败
		}
		/**
		 * { "message": "成功", "code": 200 }
		 */
		return new Message(200, "成功");
	}

	/**
	 * 充值 充值更新余额 user_account_info 充值流水记录 user_rechange_op_jnl
	 * 字段recharge_way说明：充值方式 1、微信 2、支付宝 3、银联 4、银行卡 3、其他', TODO
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ApiOperation("充值")
	@PostMapping("/rechargeAmount")
	public String rechargeAmount(HttpServletRequest request, HttpServletResponse response, @ApiParam(name = "userId", value = "用户id", required = true) Long id, @ApiParam(name = "amount", value = "充值金额", required = true) Integer amount) {

		// 返回
		/**
		 * 
		 * { "message": "成功!", "data": { "userId": 3, "deviceId":
		 * "9B4843885CDF414098694E6CC4A5F2EB", "token":
		 * "qyZqEzdeGQykYYkcyQwXNpELfLDnaif1imVnmSD+RZjQ7IOlQOrtXT8bvgI25ohQTWu5HuDK9rhRRPT3NT5PHPGFbx9nPo0O8odS1ztzrKLP2hhIF31z6HZlyJ28ktGhNN3jjjpHEsw="
		 * , "mobile": "13761031601", "nickname": "124", "lv": 100, "totalX":
		 * 2852, "head": "3606d96f9835c736dc5a04dfcf64ea22.jpg", "address":
		 * "北京通州", "gender": 0, "balance": 3323.66, "pay": 0, "payMethod": 1,
		 * "state": 1, "qrcode": "", "longitude": 1.1, "latitude": 1.1,
		 * "updated": 1468634012000, "created": 1446624510000, "distance": null,
		 * "security": "111111", "invoice": 0 }, "code": 200 }
		 * 
		 */
		return "{\r\n" + "  \"message\": \"成功!\",\r\n" + "  \"data\": {\r\n" + "    \"userId\": 3,\r\n" + "    \"deviceId\": \"9B4843885CDF414098694E6CC4A5F2EB\",\r\n" + "    \"token\": \"qyZqEzdeGQykYYkcyQwXNpELfLDnaif1imVnmSD+RZjQ7IOlQOrtXT8bvgI25ohQTWu5HuDK9rhRRPT3NT5PHPGFbx9nPo0O8odS1ztzrKLP2hhIF31z6HZlyJ28ktGhNN3jjjpHEsw=\",\r\n" + "    \"mobile\": \"13761031601\",\r\n" + "    \"nickname\": \"124\",\r\n" + "    \"lv\": 100,\r\n" + "    \"totalX\": 2852,\r\n" + "    \"head\": \"3606d96f9835c736dc5a04dfcf64ea22.jpg\",\r\n" + "    \"address\": \"北京通州\",\r\n" + "    \"gender\": 0,\r\n" + "    \"balance\": 3323.66,\r\n" + "    \"pay\": 0,\r\n" + "    \"payMethod\": 1,\r\n" + "    \"state\": 1,\r\n" + "    \"qrcode\": \"\",\r\n" + "    \"longitude\": 1.1,\r\n"
				+ "    \"latitude\": 1.1,\r\n" + "    \"updated\": 1468634012000,\r\n" + "    \"created\": 1446624510000,\r\n" + "    \"distance\": null,\r\n" + "    \"security\": \"111111\",\r\n" + "    \"invoice\": 0\r\n" + "  },\r\n" + "  \"code\": 200\r\n" + "}\r\n" + "";
	}

}
